<%@page import="com.ecp.base.bean.DynaState"%>
<%@page import="com.ecp.order.service.DynaStateService"%>
<%@page import="com.ecp.base.bean.PayMode"%>
<%@page contentType="text/html; charset=UTF-8"%>
<%@ page import="java.util.*"%>
<%@page import="java.sql.Timestamp"%>
<%@page import="com.ecp.pzh365.pay.Pkipair"%>
<%@page import="com.ecp.order.service.OrderService"%>
<%@page import="com.ecp.util.SpringUtil"%>
<%@page import="com.ecp.base.bean.Order"%>
<%@page import="com.ecp.base.service.PayRecService"%>
<%@page import="com.ecp.base.bean.PayRec"%>
<%@page import="com.ecp.util.DateUtil"%>
<%@page import="com.ecp.commons.Global"%>
<%@page import="com.ecp.pzh365.chargepay.service.ChargePayService" %>
<%@page import="com.ecp.pzh365.chargepay.service.WangYinPayService" %>
<%@page import="com.ecp.base.bean.PaySerialNumber"%>
<%@page import="com.ecp.base.service.PaySerialNumberService"%>
<%@ page import="com.ecp.util.WebUtil" %>

<%@ page import="java.net.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.util.regex.*;" %>
<jsp:useBean id="MD5" scope="request" class="beartool.MD5"/>
<%

//request.setCharacterEncoding("gbk"); //解决乱码问题


//****************************************	// MD5密钥要跟订单提交页相同，如Send.asp里的 key = "test" ,修改""号内 test 为您的密钥
											// 如果您还没有设置MD5密钥请登陆我们为您提供商户后台，地址：https://merchant3.chinabank.com.cn/
String key = WangYinPayService.key;						// 登陆后在上面的导航栏里可能找到“B2C”，在二级导航栏里有“MD5密钥设置”
											// 建议您设置一个16位以上的密钥或更高，密钥最多64位，但设置16位已经足够了
//****************************************

//获取参数
	
	 String v_oid = getParameter("v_oid",request);		// 订单号
	   
	 String v_pmode = "";	// 支付方式中文说明，如"中行长城信用卡"
	 System.out.println(request.getMethod());
	 if(request.getMethod().equalsIgnoreCase("Get")){
		 v_pmode = getV_pmodeValue(request);
	 }else if(request.getMethod().equalsIgnoreCase("Post")){
		 v_pmode = getParameter("v_pmode",request);
	 }
   String v_pstatus = getParameter("v_pstatus",request);	// 支付结果，20支付完成；30支付失败；
   String v_pstring = getParameter("v_pstring",request);	// 对支付结果的说明，成功时（v_pstatus=20）为"支付成功"，支付失败时（v_pstatus=30）为"支付失败"
	String v_amount = getParameter("v_amount",request);		// 订单实际支付金额
 String v_moneytype = getParameter("v_moneytype",request);	// 币种
	String v_md5str = getParameter("v_md5str",request);		// MD5校验码
	 String remark1 = getParameter("remark1",request);		// 备注1
	 String origRemark1 = remark1;
	 if(remark1!=null){
		 remark1 = remark1.replaceAll("^.*@", "");
	 }
	 String remark2 = getParameter("remark2",request);		// 备注2
	String tranSerialNum = getParameter("TranSerialNum",request); 

String text = v_oid+v_pstatus+v_amount+v_moneytype+key; //拼凑加密串
String v_md5text = MD5.getMD5ofStr(text).toUpperCase();

if (v_md5str.equals(v_md5text))
{
  //out.print("ok"); // 告诉服务器验证通过,停止发送
	
  	//将校验通过的数据插入日志表中
	 try{
	   	Enumeration<String> enume = request.getParameterNames();
	   	Map<String,Object> log = new HashMap<String,Object>();
	   	while(enume.hasMoreElements()){
	   		String key2 = enume.nextElement();
	   		try{
	   			log.put(key2, this.getParameter(key2,request));
	   		}catch(Exception e){
	   			e.printStackTrace();
	   			log.put("error", "1");
	   			log.put("errorMsg", key2+"关键字获取出错");
	   			System.out.println(key2+"关键字获取出错");
	   		}
	   	}
	   	this.wangYinPayService.addLog_common(PayRec.PayPartner_Wangyin, 0, WebUtil.getRemoteIP(request), log, true);
	   	//addLog(log, request.getRemoteAddr());
	   	
	   }catch(Exception e){
	   	e.printStackTrace();
	   }

   if ("20".equals(v_pstatus))
	{ 	
	   System.out.println("aaaaaa:"+"20".equals(v_pstatus));
	   boolean isChargepay = false;
	   	String orders = null;
	   	/* if(remark1!=null&&!remark1.equals("")&&remark1.equalsIgnoreCase("chargepay")){
	   		isChargepay = true;
	   		orders = v_oid.split("-")[2];
	   	}else{
	   		isChargepay = false;
	   		orders = remark1;
	   	} */
	   	String tradeNo = v_oid;
	   	System.out.println("1111");
		PaySerialNumberService paySerialNumberService = (PaySerialNumberService) SpringUtil
				.getBean("paySerialNumberService");
		DynaStateService dynaStateService = (DynaStateService) SpringUtil.getBean("dynaStateService");
		PaySerialNumber paySerialNumber = paySerialNumberService.getSerialNumberBy(tradeNo);
	   	if(origRemark1!=null&&origRemark1.indexOf(WangYinPayService.Pay_Object_Phone+"@")!=-1){
	   		isChargepay = true;
	   	}
	   	
	   	orders = paySerialNumber.getAliascode();
	   	
		OrderService os = (OrderService) SpringUtil.getBean("orderService");
		
		String aliasCode = "";
		
		String [] str = orders.split(",");
		
		if (str != null && str.length > 0) {
			Order order = null;
			PayRecService prs = (PayRecService) SpringUtil.getBean("payRecService");
			for (int i = 0; i < str.length; i++) {
				aliasCode = str[i];
				order = os.getByAliasCode(aliasCode);
				if (order != null) {
					order = os.loadOrder(order.getId());
					List<PayRec> payRecList = (List<PayRec>) order.getPayRecs();
					PayRec rec = null;
					for (PayRec payRec : payRecList) {
						if (payRec.getObjTypeId() == 102 && payRec.getObjId() == order.getId()
								&& payRec.getMoneyTypeId() == 0) {
							rec = payRec;
						}
					}

					DynaState dynaState = dynaStateService.getListByObjTypeAndObjId(102, 1, order.getId());
					if (dynaState != null) {
						boolean flag1 = false;
						if (dynaState.getStateValueId() == 1) {
							flag1 = true;
							for (PayRec payRec : order.getPayRecs()) {
								if (payRec.getObjTypeId() == 102
										&& payRec.getObjId() == order.getId()
										&& payRec.getPayModeID() == 302) {
									flag1 = false;
								}
							}
						}
						if (flag1) {
							dynaState.setStateValueId(2);
							dynaStateService.update(dynaState);
							order = os.loadOrder(order.getId());
						}
					}
					
					
					os.updateOrderPayRec(order, rec.getId(), PayRec.PayStatus_Success, false);
					//debugLogger.log("Update pay status successed on : " + order.getAliasCode());
					//debugLogger.closeLogger();
					rec.setBankID(v_pmode);
					rec.setBankName(v_pmode);
					rec.setBankOrderId(tranSerialNum);
					rec.setStatus(PayRec.PayStatus_Success);
					rec.setPayDateTime(DateUtil.getNowStringDate());
					//设置交易流水号
					rec.setExt1(tradeNo);
					rec.setPayPartner(PayRec.PayPartner_Wangyin);
					prs.update(rec);
					//话费充值
					if (isChargepay||order.getOrderTypeId()==8) {
						ChargePayService cps = (ChargePayService) SpringUtil.getBean("chargePayService");
						cps.directFill(order.getAliasCode());
					}
					
				}
			}
		}
	}else if("30".equals(v_pstatus)){
		//支付失败
		
	}
   	out.print("ok");
}else{

	out.print("error");
}
%>
<%!	

	private WangYinPayService wangYinPayService = (WangYinPayService)SpringUtil.getBean("wangYinPayService");	

	public String getParameter(String name,HttpServletRequest req){
		String oriStr = req.getParameter(name);
		if(oriStr==null){
			oriStr = "";
		}
		try{
			String str = new String(oriStr.getBytes("iso-8859-1"),"GBK");
			return str;
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}
	}
	
	Pattern p = Pattern.compile("(?:^|.*&)v_pmode=(.*?)(?:&|$)");	
	//万一请求变成get请求了用此方法解决
	public String getV_pmodeValue(HttpServletRequest req){
		System.out.println(req.getQueryString());
		Matcher m = p.matcher(req.getQueryString());
		String s = "";
		if(m.find()){
			try{
				s = new URLDecoder().decode(m.group(1),"gbk");
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		return s;
	}
%>